package com.pansoft.openplanet.util;

import com.efounder.constant.EnvironmentVariable;
import com.pansoft.hd.BIP44Util;
import com.pansoft.hd.HDWalletUtil;
import com.pansoft.openplanet.account.model.EthBean;

import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDUtils;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Wallet;
import org.web3j.crypto.WalletFile;

import java.util.List;

/**
 * 的生成HD钱包的相应代码
 * 最新的工具类请参考 HDWalletUtil
 *
 * @author yqs
 */
public class EthHDWalletUtils extends HDWalletUtil {
    private static final String TAG = "EthHDWalletUtils";


    /**
     * 使用种子生成ETH hd钱包的ecpair
     *
     * @param deterministicSeed
     * @return
     */
    public static ECKeyPair createECKeyPairFromSeed(DeterministicSeed deterministicSeed) {
        //bip44协议中 eth路径规范
        List<ChildNumber> zeroPath = HDUtils.parsePath(BIP44Util.ETHEREUM_PATH);
        //使用种子生成keychain
        DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(deterministicSeed).build();
        //创建Eth 确定性key
        DeterministicKey ethDeterministicKey = keyChain.getKeyByPath(zeroPath, true);
        //生成keyPair
        ECKeyPair ethECKeyPair = ECKeyPair.create(ethDeterministicKey.getPrivKey());
        return ethECKeyPair;
    }

    /**
     * 使用助记词和密码生成钱包文件
     *
     * @param mnemonic 助记词
     * @param passWord 密码(密码现在使用"")
     * @return
     * @throws Exception
     */
    public static EthBean generateWalletFile(String mnemonic, String passWord) throws Exception {
        //转为数组
        List<String> mnemonicList = HDWalletUtil.mnemonicString2List(mnemonic);
        //验证助记词
        HDWalletUtil.validateMnemonics(mnemonicList);
        //从助记词生成种子
        DeterministicSeed deterministicSeed = HDWalletUtil.getDeterministicSeed(mnemonicList, passWord);

        //TODO 新方式 生成eckeypair
        ECKeyPair keyPair = createECKeyPairFromSeed(deterministicSeed);
        EnvironmentVariable.setProperty("lastpublickey", keyPair.getPublicKey().toString());
        final WalletFile walletFile = Wallet.createLight("", keyPair);

        EthBean ethBean = new EthBean();
        ethBean.setEcKeyPair(keyPair);
        ethBean.setWalletFile(walletFile);
        ethBean.setEthAddress("0x" + walletFile.getAddress());
        return ethBean;
    }


    /**
     * 使用助记词和密码生成私钥（基于eth）
     *
     * @param mnemonic 助记词
     * @param passWord 密码(密码现在使用"")
     * @return
     * @throws Exception
     */
    public static String generatePrivateKey(String mnemonic, String passWord) throws Exception {
        //转为数组
        List<String> mnemonicList = HDWalletUtil.mnemonicString2List(mnemonic);
        //验证助记词
        HDWalletUtil.validateMnemonics(mnemonicList);
        //从助记词生成种子
        DeterministicSeed deterministicSeed = HDWalletUtil.getDeterministicSeed(mnemonicList, passWord);
        ECKeyPair ecKeyPair = createECKeyPairFromSeed(deterministicSeed);
        return ecKeyPair.getPrivateKey().toString(16);

    }


    /**
     * 旧代码的备份，请勿使用
     */
    //    private static String ETH_TYPE = "m/44'/60'/0'/0/0";
//    private static SecureRandom secureRandom = new SecureRandom();
    @Deprecated
    private static void createEckeyPair() {
        //todo 从种子生成eckeypair 旧方式已屏蔽  yqs 20191106
//        long creationTimeSeconds = System.currentTimeMillis() / 1000;
//        DeterministicSeed deterministicSeed = new DeterministicSeed(mnemonicList, null, passWord, creationTimeSeconds);
//        DeterministicKey dkKey = HDKeyDerivation.createMasterPrivateKey(deterministicSeed.getSeedBytes());
//        String[] pathArray = ETH_TYPE.split("/");
//        for (int i = 1; i < pathArray.length; i++) {
//            ChildNumber childNumber;
//            if (pathArray[i].endsWith("'")) {
//                int number = Integer.parseInt(pathArray[i].substring(0,
//                        pathArray[i].length() - 1));
//                childNumber = new ChildNumber(number, true);
//            } else {
//                int number = Integer.parseInt(pathArray[i]);
//                childNumber = new ChildNumber(number, false);
//            }
//            dkKey = HDKeyDerivation.deriveChildKey(dkKey, childNumber);
//        }
//        System.out.println("path " + dkKey.getPathAsString());
//        ECKeyPair keyPair = ECKeyPair.create(dkKey.getPrivKeyBytes());
    }
}